(function($){
  $.widget("mobile.dateSwiper", $.mobile.widget, {
    options: {
      inline: false,
      mode: "default",
	  popupTheme: 'c',
	  helpTheme: 'c',
	  popupActiveListItemTheme: 'b', // A kiválaszott dátum így jelenik meg
	  popupInvalidListItemTheme: 'c', // Ha érvénytelen a dátum, így jelenik meg - ha megjelenik (igazibál meg sem jelenik)
	  popupButtonTheme: 'b',
	  popupOverlayTheme: 'b',
	  popupBorderStyle: 'none', //'thin white solid',
	  popupSelectorButtonText: 'Válassz',
	  popupHelpButtonText: 'Tájékoztató',
	  popupListItemStyle: 'padding: 0 5px;',
	  popupCursor: 'pointer',
      dRows: 2 // +- ennyi sor jelenik meg a kiválasztott dátum felett és alatt
    },
	__maxValues: [2222,12,31],
	__listIds: null,
	popupId: null,
	helpId: null,
    // Mandatory method - automatically called by jQuery Mobile to initialise the widget. 
    _create: function() {
		var self = this;
        var control = this.element;
		this.popupId=this.__uniqueId(control.attr('id'));
		this.helpId=this.popupId+'_help';
		this.__listIds=[this.popupId+'_dataSwiper-Years',this.popupId+'_dataSwiper-Months',this.popupId+'_dataSwiper-Days'];
//        	valor =  parseFloat( control.attr( "value" ) ),
//            parentTheme = $.mobile.getInheritedTheme( control, "c" ),
//            theme = this.options.theme || parentTheme,
		var openButton='<a href="#'+this.popupId+'" data-role="button" data-rel="popup" data-icon="grid" data-iconpos="notext" style="float:right;">'+this.options.popupSelectorButtonText+'</a>';
		var helpButton='<a href="#'+this.helpId+'" data-role="button" data-rel="popup" data-icon="info" data-iconpos="notext" style="float:right;">'+this.options.popupHelpButtonText+'</a>';
		var buttons='<div style="float:right;">'+helpButton+openButton+'</div>';
		control.css('width','60%');
		control.css('display','inline-block');
//		control.wrap('<div xclass="ui-input-search" />').parent().append(buttons).parent().trigger('create');
		control.parent().append(buttons).parent().trigger('create');
    	$.extend( this, { // Ezek objektum szinten elérhető property-k
			control: control
		});
		this.__createPopup();
		this.__createColumns();
//		$('#'+this.options.popupId).on('afteropen',function(){ alert(7); });
		this.control.parent().find('a').on('click',function(event) { self.__onClickSelectorHandler(event); } );
		control.focus(function(event) { $(event.target).select(); });
		control.blur(this.__reformatDateHandler);
		//$(document).trigger("dateswipercreate");
    },
    ///////////////////////// private methodes
	__uniqueId: function(baseId) {
		return baseId+'_sel_popup';
	},
	__onClickSelectorHandler: function(event) {
		this.__chngDatum(0,0);
		this.__chngDatum(1,0);
		this.__chngDatum(2,0);
	},
	__createPopup: function() {
		if ($('#'+this.popupId).length==0) { // Create popup div
			var html='<div id="'+this.popupId+'" data-role="popup" data-theme="'+this.options.popupTheme+'" data-dismissible="true" data-corners="false" data-overlay-theme="'+this.options.popupOverlayTheme+'">';
			html+='<a href="#" data-rel="back" data-icon="check" data-role="button" data-theme="'+this.options.popupButtonTheme+'" data-iconpos="notext" class="ui-btn-right">Ok</a>';
			html+='<div>';
			for(var columnIndex=0; columnIndex<3; columnIndex++) {
				html+='<div id="'+this.__listIds[columnIndex]+'" style="float:left;border:'+this.options.popupBorderStyle+';"><ul data-role="listview"></ul></div>';
			}
			html+='</div>';
			html+='</div>';
			html+='<div data-role="popup" id="'+this.helpId+'" class="ui-content" data-theme="'+this.options.helpTheme+'">';
			html+='<a href="#" data-rel="back" data-role="button" data-theme="a" data-icon="delete" data-iconpos="notext" class="ui-btn-left">Bezár</a>';
			html+='<p>Válogatáshoz kattints vagy gördíts a felugró ablak oszlopaiban.</p>';
			html+='</div>';
			this.control.parents('[data-role=page]').append(html).trigger('create');
		} else {
			this.error('Popup div already exists!');
		}
	},
	error: function(msg) {
		alert('ERROR: '+msg);
	},
	__createColumns: function() { // Legenerálja a 3 oszlopot
		var datum=this.__getDatum();
		this.__createListWithEvents(0,datum);
		this.__createListWithEvents(1,datum);
		this.__createListWithEvents(2,datum);
	},
	__createListWithEvents : function(columnIndex,datum) {
		var self=this;
		var listId=this.__listIds[columnIndex];
		var list=$('#'+listId+' ul');
		var base=datum[columnIndex];
		var max=this.__maxValues[columnIndex];
		var html='';
		for (var index=0;index<=2*this.options.dRows;index++) {
			var value=this.__getListItemValue(base,index);
			var theme=(value==base)?' data-theme="'+this.options.popupActiveListItemTheme+'"':'';
			html+='<li'+theme+' class="row'+index+'" style="'+this.options.popupListItemStyle+'">'+this.__viewValue(value,max)+'</li>';
		}
		list.css('cursor',this.options.popupCursor);
		// No selectable start
		list.css('-webkit-user-select','none');
		list.css('-moz-user-select','none');
		list.css('-ms-user-select','none');
		list.css('-o-user-select','none');
		list.css('user-select','none');
		// No selectable end
		list.html(html).listview('refresh');
		for(var index=0;index<=2*this.options.dRows;index++) {
			var d=index-this.options.dRows;
			this.__setupListItemEvents(listId,index,d,columnIndex);
		}
		$('#'+this.__listIds[columnIndex]+' ul').on('swipeup', function(event) { self.__swipeHandler(1,columnIndex); } );
		$('#'+this.__listIds[columnIndex]+' ul').on('swipedown', function(event) { self.__swipeHandler(-1,columnIndex); } );
	},
	__setupListItemEvents: function(listId,index,d,columnIndex) {
		var self=this;
		$('#'+listId+' .row'+index).on('click', function(event) { self.__clickEventHandler(d,columnIndex); } );
		if (index==this.options.dRows) {
			$('#'+listId+' .row'+index).on('dblclick', function(event) { self.__doubleClickEventHandler(event,0,columnIndex); } );
		}
	},
	__swipeHandler: function(d,columnIndex) {
		this.__chngDatum(columnIndex,d);
	},
	__clickEventHandler: function(d,columnIndex) {
		this.__chngDatum(columnIndex,d);
	},
	__doubleClickEventHandler: function(event,d,columnIndex) {
		this.__chngDatum(columnIndex,d);
		$(event.target).parents(":jqmData(role='popup')").popup('close');
	},
	__chngDatum: function(columnIndex,d) {
		var listId=this.__listIds[columnIndex];
		var datum=this.__getDatum();
		datum[columnIndex]+=d;
		if (datum[columnIndex]>0 && datum[columnIndex]<=this.__maxValues[columnIndex]) { // Ok, mehet
			this.__setDatum(datum);
			this.__refreshList(listId,columnIndex);//event.target);
			this.__revalidateDays();
		}
	},
	__viewValue: function(value,max) { // in list
		if (value>0 && value<=max) {
			return this.__view2(value)+'.';
		} else {
			return '&nbsp;';
		}
	},
	__view2: function(value) {
		if (value<10) {
			return '0'+value;
		} else {
			return value;
		}
	},
	__setDatum: function(datum) {
		var ev=datum[0];
		var ho=datum[1];
		var nap=datum[2];
		if (this.__isValidDate(ev,ho,nap)) {
			this.control.val(this.__viewDatum(ev,ho,nap));
		}
	},
	__viewDatum: function(ev,ho,nap) {
		return ev+'.'+this.__view2(ho)+'.'+this.__view2(nap)+'.';
	},
	__isValidDate: function(ev,ho,nap) {
		return (nap>0) && (nap<=this.__getMaxNap(ev,ho));
	},
	__getMaxNap: function(ev,ho) {
		var monthStart = new Date(ev, ho-1, 1);
		var monthEnd = new Date(ev, ho, 1);
		return Math.round((monthEnd - monthStart) / (1000 * 60 * 60 * 24));
	},
	__revalidateDays: function() {
		var datum=this.__getDatum();
		var ev=datum[0];
		var ho=datum[1];
		var nap=datum[2];
		var theme=this.__isValidDate(ev,ho,nap)?this.options.popupActiveListItemTheme:this.options.popupInvalidListItemTheme;
		$('#'+this.__listIds[0]+this.options.dRows).removeClass('ui-btn-up-c').removeClass('ui-btn-up-b').addClass('ui-btn-up-'+theme).attr('data-theme', theme).trigger('create');
		$('#'+this.__listIds[1]+this.options.dRows).removeClass('ui-btn-up-c').removeClass('ui-btn-up-b').addClass('ui-btn-up-'+theme).attr('data-theme', theme).trigger('create');
		$('#'+this.__listIds[2]+this.options.dRows).removeClass('ui-btn-up-c').removeClass('ui-btn-up-b').addClass('ui-btn-up-'+theme).attr('data-theme', theme).trigger('create');
	},
	__refreshList: function(listId,columnIndex) {
		var list=$('#'+listId+' ul');
		var datum=this.__getDatum();
		var base=datum[columnIndex];
		var max=this.__maxValues[columnIndex];
		for (var index=0;index<=2*this.options.dRows;index++) {
			var value=this.__getListItemValue(base,index);
			$('#'+listId+' .row'+index).html(this.__viewValue(value,max));
		}
		list.listview('refresh');
	},
	__getListItemValue: function(base,index) {
		return base-this.options.dRows+index;
	},
	__getDatum: function() {
		var re = /^(\d+)[^\d]+(\d+)[^\d]+(\d+)([^\d]+|)$/;
		var datumValue=this.control.val();
		var mtchs=datumValue.match(re);
		if (mtchs) { // Igen, ez dátum
			var ev=Math.round(mtchs[1]);
			var ho=Math.round(mtchs[2]);
	  		var nap=Math.round(mtchs[3]);
			return new Array(ev,ho,nap);
		} else {
			return new Array(1991,03,21);
		}
	},
	__reformatDateHandler: function(event) {
		var input=$(event.target);
		var re = /^(\d+)[^\d]+(\d+)[^\d]+(\d+)([^\d]+|)$/;
		var datum=input.val();
		var mtchs=datum.match(re);
		if (mtchs) { // Igen, ez dátum
			var ev=Math.round(mtchs[1]);
			var ho=Math.round(mtchs[2]);
			if (ho<1) {
				ho=1;
			}
			if (ho>12) {
				ho=12;
			}
			var nap=Math.round(mtchs[3]);
			if (nap<1) {
				nap=1;
			}
			if (nap>getMaxNap(ev,ho)) {
				nap=getMaxNap(ev,ho);
			}
			input.val(ev+'.'+ho+'.'+nap+'.');
		} else {
			input.focus();
		}
	}
  });
  // </em> Handler which initialises all widget instances during page creation. 
  $(document).bind("pagecreate", function(e) {
//    $(document).trigger("mywidgetbeforecreate");
	return $(":jqmData(role='date')", e.target).dateSwiper({dRows:3});
  });
})(jQuery);
